<?php


namespace App\HttpController\Service;


use App\HttpController\Base\AuthBase;
use App\Service\ResourceService;
use App\Service\UploadService;
use App\Utility\McHelper;

class Upload extends AuthBase
{
    public function upload()
    {
        $raw_data = $this->getRawData();
        $field = 'file';
        if (isset($raw_data['field'])) {
            $field = $raw_data['field'];
        }

        $file = $this->request()->getUploadedFile($field);
        if (empty($file)) {
            return $this->error('上传失败');
        }
        $md5 = md5_file($file->getTempName());

        $result = ResourceService::getResourceByMd5($md5);

        if (!empty($result)) {
            $ret_data = [
                'rid' => $result['id'],
                'path' => $result['path'],
                'url' => McHelper::getFileUrl($result)
            ];
            return $this->success('文件上传成功', $ret_data);
        }
        $ret = UploadService::uploadToQiniu($file, $this->user_id);
        if (!empty($ret)) {
            $ret['user_id'] = $this->user_id;
            $resource_id = ResourceService::savaResource($ret);

            $ret_data = [
                'rid' => $resource_id,
                'path' => $ret['path'],
                'url' => $ret['url']
            ];
            return $this->success('上传成功', $ret_data);
        }

    }

}